use serde::{Deserialize, Serialize};
use walkdir::WalkDir;
#[derive(Debug, Deserialize, Serialize,Clone)]
pub struct Config {
    pub database: Database,
    pub server: Server,
}

#[derive(Debug, Deserialize, Serialize,Clone)]
pub struct Database {
    pub host: String,
    pub port: u16,
    pub username: String,
    pub password: String,
}

#[derive(Debug, Deserialize, Serialize,Clone)]
pub struct Server {
    pub port: u16,
}
pub fn get_config(data: &str) -> Result<Config, Box<dyn std::error::Error>> {
    let result = serde_yaml::from_str(data)?;
    Ok(result)
}

const CONFIG_FILE_NAME: &str = "application.yml";

pub async fn load_config() -> Result<String, Box<dyn std::error::Error>> {
    let current_dir = std::env::current_dir()?;

    // 使用 walkdir 递归遍历当前目录下的所有文件
    for entry in WalkDir::new(&current_dir)
        .into_iter()
        .filter_map(|e| e.ok()) // 忽略错误条目
        .filter(|e| e.file_type().is_file()) // 只处理文件
    {
        if let Some(file_name) = entry.file_name().to_str() {
            if file_name == CONFIG_FILE_NAME {
                let config_path = entry.path();
                let content = std::fs::read_to_string(config_path.to_string_lossy().to_string())?;
                return Ok(content);
            }
        }
    }

    panic!("Failed to load config from: {}", CONFIG_FILE_NAME);
}
